﻿using BCC.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using BCC.Model.user;
using BCC.Common;
using System.Configuration;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using BCC.Model.ModelsOut;
using BCC.Common.AuthorizationUtils;

namespace BCC.ViewModel.login
{
    public class loginVM
    {
        //protected static bccContext context = new Model.bccContext();
        public static string serverAddress = ConfigurationManager.AppSettings["serverAddress"].Trim();

        /// <summary>
        /// 根据账号查询信息并登录
        /// </summary>
        /// <param name="sendAccount"></param>
        /// <param name="receiveAccount"></param>
        /// <returns></returns>
        public static BCCUser selLogin(string Account, string pwd)
        {
            try
            {
                #region 之前代码
                //var password = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
                //string pwdMD5 = string.Empty;
                //using (var md5 = MD5.Create())
                //{
                //    var result = md5.ComputeHash(Encoding.UTF8.GetBytes(pwd));
                //    var strResult = BitConverter.ToString(result);
                //    pwdMD5 = strResult.Replace("-", "");
                //}

                //var bccUser = context.UUser.Where(i => i.Password == pwdMD5 && i.Account == Account).AsEnumerable().Select(item => new BCCUser
                //{
                //    Id = item.Id,
                //    Account=item.Account,
                //    UserName=item.UserName,
                //    UserSign=item.UserSign,
                //    Address=item.Address,
                //    Telephone=item.Telephone,
                //    Mail=item.Mail,
                //    RoleId=item.RoleId
                //}).FirstOrDefault();
                #endregion

                var url = serverAddress + $"api/Login/selLogin?Account={Account}&pwd={pwd}";
                var rs = Utils.Get(url);

                var bccUser = JsonConvert.DeserializeObject<BaseOut>(rs);

                if (bccUser.code == "true" && bccUser.content != null)
                {
                    var user = JsonConvert.DeserializeObject<BCCUser>(bccUser.content.ToString());
                    if (user != null && !string.IsNullOrEmpty(user.token)) 
                    {
                        AuthorizationUtils.authorization = user.token; 
                    }
                    return user;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

    }
}
